#!/usr/bin/env bash

next_python () {
	if [ "$POL_PYTHON" = "$1" ]; then
		# will pick the next one
		POL_PYTHON=""
	elif [ -z "$POL_PYTHON" ]; then
		POL_PYTHON="$1"
	fi
}

search_python () {
	POL_PYTHON=""
	while true; do
		# list of interpreter names to try, in order
		next_python "python3"
		next_python "python"
		next_python "python2.7"
		next_python "python2.6"
		next_python "python2"
		next_python "none"
	
		if [ "$POL_PYTHON" = "none" ]; then
			echo "Please install python before trying to run this program" 1>&2
			return 1
		fi                   
	
		echo -n "Looking for $POL_PYTHON... " 1>&2
		if [ "$(command -v $POL_PYTHON)" ]; then
			local Version=$($POL_PYTHON --version 2>&1 |tail -n 1|sed -e 's/^Python //')
			echo -n "$Version - " 1>&2
			case "$Version" in
			    2.6|2.6.*|2.7|2.7.*|3.*)
	                        if test_python; then
				        echo "selected" 1>&2
					return 0
				fi
				echo "failed tests" 1>&2
				;;
			    2.5|2.5.*)
			        # Compatibility broken a while ago
				echo "skipped" 1>&2
				;;
			    *)
				echo "unexpected version" 1>&2
				;;
			esac
		else
			# Interpreter name not found
			echo "" 1>&2
		fi
	done
}

test_python () {
    "$POL_PYTHON" "$POLDIR/python/check_python.py"
}
